package com.ssm.service.websocket;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.socket.CloseStatus;
import org.springframework.web.socket.TextMessage;
import org.springframework.web.socket.WebSocketSession;
import org.springframework.web.socket.handler.TextWebSocketHandler;

/**
 * websocket消息处理类
 * @author gaopengchao
 * 2019年7月24日
 */
public class ChatMessageHandler extends TextWebSocketHandler
{
    //保存所有与客户端的会话
    public static ConcurrentMap<String, WebSocketSession> webSocketMap = new ConcurrentHashMap<>();

    public final static Logger logger = (Logger) LoggerFactory.getLogger(ChatMessageHandler.class);
    
    /**
     * 连接成功时候，会触发UI上onopen方法
     */
    @Override
    public void afterConnectionEstablished(WebSocketSession session) throws Exception
    {
        logger.info("connect to the websocket success......" + session.getUri().getQuery());
        webSocketMap.put(session.getUri().getQuery(), session);
        
    }

    /**
     * 在UI在用js调用websocket.send()时候，会调用该方法
     * 接收到消息时
     */
    @Override
    protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception
    {
    }

    /**
     * 连接发生异常
     */
    @Override
    public void handleTransportError(WebSocketSession session, Throwable exception) throws Exception
    {
        String name = session.getUri().getQuery();
        if (session.isOpen())
        {
            session.close();
        }
        logger.debug("websocket connection closed......" + name);
        webSocketMap.remove(name);
    }

    /**
     * 连接关闭
     */
    @Override
    public void afterConnectionClosed(WebSocketSession session, CloseStatus closeStatus) throws Exception
    {
        String name = session.getUri().getQuery();
        logger.debug("websocket connection closed......");
        webSocketMap.remove(name);
    }
    @Override
    public boolean supportsPartialMessages()
    {
        return false;
    }
    
    /**
     * 群发消息给web客户端
     * 
     * @param message TextMessage 
     * @param containStr 包含的字符串
     */
    public static void sendMessageToWeb(String message,String containStr)
    {
        TextMessage tm = new TextMessage(message.getBytes());
        for (WebSocketSession session : webSocketMap.values())
        {
            //给web客户端群发消息
            if (session.getUri().getQuery().contains(containStr))
            {
                try
                {
                    session.sendMessage(tm);
                }
                catch(IOException e)
                {
                    e.printStackTrace();
                    logger.debug("websocket send message error ......" + session.getUri().getQuery());
                    webSocketMap.remove(session.getUri().getQuery());
                }
            }
        }
    }
}
